﻿using IOP.SgrA;
using IOP.SgrA.SilkNet.Vulkan;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Silk.NET.Vulkan;
using System;
using System.Collections.Generic;
using System.IO;
using System.Numerics;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace VkSample82
{
    [ModulePriority(ModulePriority.ISEA)]
    public class DescriptorModule : VulkanModule, IVulkanRenderWapperModule
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="lightManager"></param>
        public DescriptorModule()
        {
        }

        public VulkanRenderWapper RenderWapper { get; set; }

        protected override Task Load(VulkanGraphicsManager graphicsManager)
        {
            try
            {
                var lDevice = graphicsManager.VulkanDevice;
                var pipeCache = lDevice.PipelineCache;
                var disapatcher = RenderWapper.GetRenderDispatcher<VulkanSwapchainRenderDispatcher>();
                var pass = disapatcher.GetSwapchainRenderPass();
                var area = RenderWapper.RenderArea;
                var basePath = AppContext.BaseDirectory;
                var descriptorPath = Path.Combine(basePath, "Assets");

                var command = lDevice.CreateCommandPool((device, option) =>
                {
                    option.Flags = CommandPoolCreateFlags.CommandPoolCreateResetCommandBufferBit;
                    option.QueueFamilyIndex = device.WorkQueues[0].FamilyIndex;
                }).CreatePrimaryCommandBuffer();
                var fence = lDevice.CreateFence();
                var mainGroup = graphicsManager.CreatePrimaryRenderGroup("MainRenderGroup", null)
                    .Binding(command, lDevice, pass, new Semaphore[] { disapatcher.ImageAvailableSemaphore, disapatcher.RenderFinishSemaphore }, new Fence[] { fence.RawHandle });
                mainGroup.CreateGroupRenderingAction((builder) => builder.UseMiddleware<MainGroupRenderingMiddleware>());

                var aspect = (float)area.Width / area.Height;
                var camera = graphicsManager.CreateCamera("main", new Vector3(0, 0, 600.0f), new Vector3(0, 0, 0), new Vector3(0, 1, 0));
                camera.SetProjectMatrix(-aspect, 1.0f, 4.0f, 5000);
                camera.SetViewport(0, 0, area.Width, area.Height, 0, 1);

                RenderWapper.CreateAndCutScene<Scene>("main", mainGroup, typeof(EarthSystem), typeof(InputSystem), typeof(MoonSystem), typeof(StarSystem));
            }
            catch (Exception e)
            {
                graphicsManager.Logger.LogError(e.Message + "\r\n" + e.StackTrace);
            }
            return Task.CompletedTask;
        }

        protected override Task Unload(VulkanGraphicsManager manager)
        {
            return Task.CompletedTask;
        }
    }
}
